package com.example.springboot.controller;

import com.aliyuncs.exceptions.ClientException;
import com.example.springboot.MD5Until;
import com.example.springboot.UUIDUtils;
import com.example.springboot.aliyun;
import com.example.springboot.bean.Register;
import com.example.springboot.bean.Result;
import com.example.springboot.bean.User;
import com.example.springboot.repository.MailRepository;
import com.example.springboot.service.LoginService;
import com.example.springboot.service.MailService;
import com.example.springboot.service.UserService;
import com.example.springboot.yzmServlet;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.List;

/**
 * @program: supermarketparent
 * @description:
 * @author: MajorMKN
 * @create: 2019-10-22 16:26
 **/
@RestController
public class yzmController {

    @Resource
    private MailService mailService;
    @Resource
    private LoginService loginService;

    @RequestMapping("/code")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception{
        HttpSession session=request.getSession();
        //利用图片工具生成图片
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = yzmServlet.createImage();
        //将验证码存入Session
        session.setAttribute("imageCode",objs[0]);

        //将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }


    @RequestMapping("/login")
    public Result login(String yzm,String username,String password){
        String mdPassword = MD5Until.md5(password);
        Register register = loginService.selectRegister(username);
        System.out.println(username+" "+ password+" "+yzm);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String vcode = (String) attributes.getRequest().getSession().getAttribute("imageCode");

        if (register != null){
            if (!mdPassword.equals(register.getPassword())){
                return new Result(false,"密码错误");
            }else if (!vcode.toString().equalsIgnoreCase(yzm)){
                return new Result(false,"验证码错误");
            }
            return new Result(true,"true");
        }
        return new Result(false,"用户不存在");
    }


    @RequestMapping("/selectPhone") //
    public Result selectPhone(String phone){
        System.out.println(phone + " ");
        List<Register> result = loginService.selectPhone(phone);


        if (result.size() != 0){
            return new Result(false,"该手机已注册");
        }else{
            return new Result(true, "成功");
        }
    }

    @RequestMapping("/checkName")
    public Result checkName(String username,String yzm){
        User user=new User();

        List<Register> list = loginService.selectName(username);

        //获取生成的验证码vcode
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String vcode = (String) attributes.getRequest().getSession().getAttribute("imageCode");
        System.out.println(yzm + " "+vcode);

        if (list.size() != 0){
            return new Result(false,"该用户名已经被注册");
        }else if (!yzm.equalsIgnoreCase(vcode)){
            return new Result(false,"验证码输入错误");
        }else {
            return new Result(true,"注册成功，请激活");
        }
    }

    /**
     *校验邮箱中的code激活账户
     * 首先根据激活码code查询用户，之后再把状态修改为"1"
     */
    @RequestMapping(value = "/checkCode")
    public ModelAndView checkCode(String code){
        Register code1 = loginService.checkCode(code);
        System.out.println(code1.getUsername());
        //如果用户不等于null，把用户状态修改status=1
        if (code1 != null){
            code1.setStatus(1);
            //把code验证码清空，已经不需要了
            code1.setCode("");
            loginService.updateUserStatus(code1);

            ModelAndView mv = new ModelAndView("login");
            return mv;
        }
        ModelAndView mv = new ModelAndView("error");
        return mv;
    }

    @RequestMapping("/selectAll")
    public List<Register> selectAll(){
        return loginService.findAll();
    }

    @RequestMapping("/insertRegister")
    public Result insertRegister(@RequestBody Register register){

        try{
            register.setPassword(MD5Until.md5(register.getPassword()));
            System.out.println(register.getPassword());
            register.setStatus(0);
            register.setCode(UUIDUtils.getUUID().toString());
            loginService.insertRegister(register);

            String code = register.getCode();
            System.out.println("code:"+code);
            //主题
            String subject = "来自用户管理网站的激活邮件";
            //user/checkCode?code=code(激活码)是我们点击邮件链接之后根据激活码查询用户，如果存在说明一致，将用户状态修改为“1”激活
            //上面的激活码发送到用户注册邮箱
            String context = "<a href=http://localhost:8080/checkCode?code="+code+">激活请点击:"+code+"</a>";
            //发送激活邮件
            mailService.sendHtmlMail (register.getEmail(),subject,context);


            return new Result(true,"success");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"fail");
        }
    }
    //手机验证码验证
    @RequestMapping("/phoneCheck")
    public Result phoneCheck(String phone) throws ClientException {
        List<Register> list = loginService.selectPhone(phone);
        String a = aliyun.checkPhoneYzm(phone).toString();
        System.out.println(a);
        if (list.size() != 0){
            return new Result(true,a);
        }else {
            return new Result(false,"该手机号没有注册");
        }
    }
}
